package com.jarvis.core.finder;

import cn.hutool.core.collection.CollUtil;
import com.jarvis.core.plugin.PluginDefine;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

/**
 * 通过ServiceLoader加载
 * @author xuxukang
 * @date 2019-07-04 11:33
 */
public enum PluginFinder {
  INSTANCE;

  private volatile List<PluginDefine>  pluginDefines = new ArrayList<>();

  /**
   * 获取添加到classpath的插件列表
   * @param reload 是否直接重新加载
   */
  public List<PluginDefine> findPluginDefines(boolean reload) {
    if (reload) {
      this.pluginDefines = reloadPluginDefines();
    } else {
      if (CollUtil.isEmpty(pluginDefines)) {
        synchronized (INSTANCE) {
          if (CollUtil.isEmpty(pluginDefines)) {
            pluginDefines = reloadPluginDefines();
          }
        }
      }
    }

    return pluginDefines;
  }

  private List<PluginDefine> reloadPluginDefines() {
    List<PluginDefine> list = new ArrayList<>();
    ServiceLoader<PluginDefine> pluginServices = ServiceLoader
      .load(PluginDefine.class);
    for (PluginDefine pluginDefine : pluginServices) {
      list.add(pluginDefine);
    }
    return list;
  }

}
